package com.example.yichuangyun.ui.activity.business;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivityProductBinding;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.ToastHelper;
import com.example.yichuangyun.utils.producttreelist.ProductNodeModel;
import com.example.yichuangyun.utils.producttreelist.ProductTreeAdapter;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * 意向产品
 */
public class ProductActivity extends BaseActivity<ActivityProductBinding, BaseViewModel> {

    private final List<ProductNodeModel> mData = new ArrayList<>();
    private ProductTreeAdapter adapter;
    private HashSet<ProductNodeModel> chooseData = new HashSet<>();
    private int flag = 0;
    private boolean isEditProduct = false;
    private int category;
    private String poolId;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            flag = bundle.getInt(Constant.flagKey, 0);
            if (bundle.getSerializable(Constant.listKey) != null) {
                chooseData = (HashSet<ProductNodeModel>) bundle.getSerializable(Constant.listKey);
            }
            isEditProduct = bundle.getBoolean(Constant.isEditProductKey, false);
            if (flag == 0) {
                category = bundle.getInt(Constant.categoryKey);
                poolId = bundle.getString(Constant.poolIdKey, "");
            }
        }

        initTitleBar(flag == 0 ? getString(R.string.idea_product) : flag == 1 ? getString(R.string.business_from) : getString(R.string.contacts_from));
        binding.etSearch.setHint(flag == 0 ? getString(R.string.please_input_product_name)
                : flag == 1 ? getString(R.string.please_input_business_from_name)
                : getString(R.string.please_input_contacts_from_name));
        if (flag == 2) {
            binding.etSearch.setVisibility(View.GONE);
        }
        adapter = new ProductTreeAdapter(context, mData, 2, flag);
        binding.recyclerView.setAdapter(adapter);
        getProductList("");
    }

    private void getProductList(String keywords) {
        showLoadingDialog();
        RetrofitHelper.getInstance().execute(flag == 0
                        ? RetrofitHelper.getService().getProductTree(keywords, category)
                        : flag == 1 ? RetrofitHelper.getService().getBusinessSource(keywords)
                        : RetrofitHelper.getService().getContactsSource(),
                new MyObserver<HttpRespond<List<ProductNodeModel>>>() {
                    @Override
                    protected void onSuccess(HttpRespond<List<ProductNodeModel>> listHttpRespond) {
                        if (Constant.SUCCESS == listHttpRespond.code) {
                            if (listHttpRespond.data == null || listHttpRespond.data.size() == 0) {
                                binding.recyclerView.setVisibility(View.GONE);
                                binding.llEmpty.setVisibility(View.VISIBLE);
                            } else {
                                binding.recyclerView.setVisibility(View.VISIBLE);
                                binding.llEmpty.setVisibility(View.GONE);
                                for (int i = 0; i < listHttpRespond.data.size(); i++) {
                                    ProductNodeModel node = listHttpRespond.data.get(i);
                                    if (flag == 0) {
                                        mData.add(new ProductNodeModel(node.getTitle(), node.getId(), node.getParentId(), node.getProductid(), node.getPoolid(), node.getType(), node.getFlag(), node.getParentProductId()));
                                    } else {
                                        mData.add(new ProductNodeModel(node.getLabel(), node.getId(), node.getParentId(), node.getUseState()));
                                    }
                                    initList(listHttpRespond.data.get(i).getChildren());
                                }
                                if (chooseData.size() > 0) {
                                    for (ProductNodeModel m : mData) {
                                        for (ProductNodeModel n : chooseData) {
                                            if (flag == 0) {
                                                if (m.getProductid().equals(n.getProductid()) && m.getPoolid().equals(n.getPoolid())) {
                                                    m.setChecked(true);
                                                }
                                            } else {
                                                if (m.getId().equals(n.getId())) {
                                                    m.setChecked(true);
                                                }
                                            }
                                        }
                                        // 编辑商机时不能修改意向产品大类
                                        if (isEditProduct && !m.getPoolid().equals(chooseData.iterator().next().getPoolid())) {
                                            m.setUseState(1);
                                        }
                                    }
                                    changeBtnStatus();
                                } else {
                                    // 编辑商机时切换业务类型 不能修改意向产品大类
                                    if (isEditProduct) {
                                        for (ProductNodeModel productNodeModel : mData) {
                                            if (isEditProduct && !poolId.equals(productNodeModel.getPoolid())) {
                                                productNodeModel.setUseState(1);
                                            }
                                        }
                                    }
                                }
                                adapter.addDataAll(mData);
                            }
                        }
                        dismissLoadingDialog();
                    }

                    @Override
                    protected void onFail(Throwable e) {
                        super.onFail(e);
                        ToastHelper.show(e.getMessage());
                        dismissLoadingDialog();
                    }
                });
    }

    @Override
    protected void initClick() {
        binding.btnConfirm.setOnClickListener(v -> {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable(Constant.listKey, chooseData);
            intent.putExtras(bundle);
            setResult(RESULT_OK, intent);
            finish();
        });

        adapter.setOnOnCheckListener((model) -> {
            if (flag == 0) {
                if (chooseData.size() > 0 && !model.getPoolid().equals(chooseData.iterator().next().getPoolid())) {
                    chooseData.clear();
                }
                if (model.isChecked()) {
                    model.setParentId(model.getParentProductId());
                    chooseData.add(model);
                } else {
                    chooseData.removeIf(productNodeModel -> productNodeModel.getProductid().equals(model.getProductid()));
                }
            } else {
                chooseData.clear();
                if (model.isChecked()) {
                    chooseData.add(model);
                }
            }
            changeBtnStatus();
        });

        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                // 关闭软键盘
                CommonUtil.closeKeyboard(ProductActivity.this);
                String content = binding.etSearch.getText().toString();
                mData.clear();
                getProductList(content);
                return true;
            }
            return false;
        });

        binding.etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                binding.ivClear.setVisibility(editable.toString().length() == 0 ? View.GONE : View.VISIBLE);
            }
        });

        binding.ivClear.setOnClickListener(view -> {
            binding.etSearch.setText("");
            mData.clear();
            getProductList("");
        });
    }

    private void initList(List<ProductNodeModel> list) {
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                ProductNodeModel node = list.get(i);
                if (flag == 0) {
                    mData.add(new ProductNodeModel(node.getTitle(), node.getId(), node.getParentId(),
                            node.getProductid(), node.getPoolid(), node.getType(), node.getFlag(), node.getParentProductId()));
                } else {
                    // String title, String id, String parentId
                    mData.add(new ProductNodeModel(node.getLabel(), node.getId(), node.getParentId(), node.getUseState()));
                }

                initList(node.getChildren());
            }
        }
    }

    private void changeBtnStatus() {
        if (chooseData.size() > 0) {
            binding.btnConfirm.setEnabled(true);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_sel);
        } else {
            binding.btnConfirm.setEnabled(false);
            binding.btnConfirm.setBackgroundResource(R.drawable.shape_button_def);
        }
    }
}